package com.zenithmind.user.service.domain.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zenithmind.user.mapper.UserMapper;
import com.zenithmind.user.pojo.domain.User;
import com.zenithmind.user.service.domain.UserDomainService;
import com.zenithmind.user.utils.PasswordUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户领域服务实现
 * 遵循依赖倒置原则：依赖抽象的Mapper接口
 * 遵循单一职责原则：只处理用户核心业务逻辑
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDomainServiceImpl implements UserDomainService {
    
    private final UserMapper userMapper;
    
    @Override
    public boolean isUsernameUnique(String username, String excludeUserId) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        if (excludeUserId != null) {
            wrapper.ne(User::getId, excludeUserId);
        }
        return userMapper.selectCount(wrapper) == 0;
    }
    
    @Override
    public boolean isEmailUnique(String email, String excludeUserId) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email);
        if (excludeUserId != null) {
            wrapper.ne(User::getId, excludeUserId);
        }
        return userMapper.selectCount(wrapper) == 0;
    }
    
    @Override
    public User createUser(String username, String password, String email) {
        // 验证用户名和邮箱唯一性
        if (!isUsernameUnique(username, null)) {
            throw new IllegalArgumentException("用户名已存在");
        }
        if (!isEmailUnique(email, null)) {
            throw new IllegalArgumentException("邮箱已存在");
        }
        
        // 加密密码
        String hashedPassword = PasswordUtils.encryption(password);
        
        // 创建用户对象
        User user = new User(username, hashedPassword, email);
        
        // 保存到数据库
        userMapper.insert(user);
        
        log.info("创建用户成功: username={}, email={}", username, email);
        return user;
    }
    
    @Override
    public boolean validatePassword(User user, String password) {
        if (user == null || password == null) {
            return false;
        }
        return PasswordUtils.compare(password, user.getPassword());
    }
    
    @Override
    public void updatePassword(User user, String newPassword) {
        if (user == null || newPassword == null) {
            throw new IllegalArgumentException("用户和密码不能为空");
        }
        
        String hashedPassword = PasswordUtils.encryption(newPassword);
        user.updatePassword(hashedPassword);
        
        userMapper.updateById(user);
        log.info("更新用户密码成功: userId={}", user.getId());
    }
    
    @Override
    public void recordLogin(User user, String ipAddress) {
        if (user == null) {
            return;
        }
        
        user.recordLogin(ipAddress);
        userMapper.updateById(user);
        
        log.info("记录用户登录: userId={}, ip={}", user.getId(), ipAddress);
    }
    
    @Override
    public boolean canLogin(User user) {
        if (user == null) {
            return false;
        }
        return user.isActive();
    }
    
    @Override
    public boolean updateUserStorage(User user, long deltaSize) {
        if (user == null) {
            return false;
        }
        
        boolean success = user.updateStorageUsed(deltaSize);
        if (success) {
            userMapper.updateById(user);
            log.info("更新用户存储使用量: userId={}, delta={}, current={}", 
                    user.getId(), deltaSize, user.getStorageUsed());
        }
        
        return success;
    }
}
